package io.renren.modules.sys.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.renren.common.exception.RRException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.entity.BannerEntity;
import io.renren.modules.sys.service.BannerService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;




/**
 * 
 * 
 * @author wangyi
 * @email 794651397@qq.com
 * @date 2018-02-24 10:46:32
 */
@RestController
@RequestMapping("/sys/banner")
public class BannerController {
	@Autowired
	private BannerService bannerService;
	
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);

		List<BannerEntity> bannerList = bannerService.queryList(query);
		int total = bannerService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(bannerList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	public R info(@PathVariable("id") Long id){
		BannerEntity banner = bannerService.queryObject(id);
		
		return R.ok().put("banner", banner);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public R save(@RequestBody BannerEntity banner){
        banner.setCreateTime(new Date());
        banner.setStatus(0);
		bannerService.save(banner);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	public R update(@RequestBody BannerEntity banner){
	    if(banner.getStatus()==1){
            HashMap<String,Object> map=new HashMap<>();
            map.put("status",1);
	        int count=bannerService.queryTotal(map);
	        if(count>=5){
                throw new RRException("上架展示不能大于5张banner");
            }
            banner.setReleaseTime(new Date());
        }
        banner.setUpdateTime(new Date());
		bannerService.update(banner);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	public R delete(@RequestBody Long[] ids){
		bannerService.deleteBatch(ids);
		
		return R.ok();
	}
	
}
